import { defineStore } from "pinia";
import { asyncRoutes, constantRoutes } from "../../router";
import { useStore } from "./login";
import { removeAccessToken } from "@/utils/accessToken";
import { convertRouter, filterRoutes } from '@/utils/routes'
export const useRouterStore = defineStore("router", {
  state: () => {
    return {
      routes: [],
      partialRoutes: [],
    };
  },
  getters: {
    getRoutes:(state)=> {
      return state.routes;
    },
    getPartialRoutes() {
      return this.partialRoutes;
    },
  },
  actions: {
    /**
     * @description intelligence模式设置路由
     * @param {*} { commit }
     * @returns
     */
    async setRoutes() {
      const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]);
      this.routes = finallyRoutes;
      return [...asyncRoutes];
    },

    /**
     * @description all模式设置路由
     * @param {*} { commit }
     * @returns
     */
    async setAllRoutes() {
      // let { data } = await getRouterList()
      if (data[data.length - 1].path !== "*")
        data.push({ path: "*", redirect: "/404", hidden: true });
      const asyncRoutes = convertRouter(data);
      const finallyRoutes = filterRoutes([...constantRoutes, ...asyncRoutes]);
      this.routes = finallyRoutes;
      return [...asyncRoutes];
    },

    /**
     * @description 重置accessToken、roles、ability、router等
     * @param {*} { commit, dispatch }
     */
    async resetAll() {
      const store = useStore();
      store.setAccessToken("");
      await store.setFull(false);
      await store.setRole([]);
      await store.setAbility([]);
      removeAccessToken();
    },
    //   try {
    //     const res = await api.getUser()
    //     if (res.code === 0) {
    //       const { id, name, avatar, role } = res.data
    //       this.userInfo = { id, name, avatar, role }
    //       return Promise.resolve(res.data)
    //     }
    //     else {
    //       return Promise.reject(res)
    //     }
    //   }
    //   catch (error) {
    //     return Promise.reject(error)
    //   }
  },
});
